package com.itstudio.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itstudio.portal.entity.DictRegion;
import com.itstudio.portal.entity.RestResponse;
import com.itstudio.portal.entity.dto.AddressDetailDto;
import com.itstudio.portal.enums.HttpCodeEnum;
import com.itstudio.portal.mapper.DictRegionMapper;
import com.itstudio.portal.service.DictRegionService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Stack;

/**
 * (DictRegion)表服务实现类
 *
 * @author zhaopengbo
 * @since 2024-11-14 21:51:22
 */
@Service("dictRegionService")
public class DictRegionServiceImpl implements DictRegionService {
    @Resource
    private DictRegionMapper dictRegionMapper;

    @Override
    public RestResponse getRegionTree(long parentCode) {
        LambdaQueryWrapper<DictRegion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictRegion::getParentCode, parentCode);
        List<DictRegion> dictRegions = dictRegionMapper.selectList(queryWrapper);
        // 当没有子节点时返回完整地址
        if (dictRegions == null || dictRegions.isEmpty()) {
            long code = parentCode;
            Stack<String> fullRegionStack = new Stack<>();
            StringBuilder fullRegion = new StringBuilder();
            while (code != 0) {

                DictRegion dictRegion = dictRegionMapper.selectById(code);
                if (dictRegion == null) {
                    return RestResponse.failure(HttpCodeEnum.UNKNOWN_ERROR);
                }
                code = dictRegion.getParentCode();
                fullRegionStack.push(dictRegion.getName());
            }
            while (!fullRegionStack.isEmpty()) {
                fullRegion.append(fullRegionStack.pop()+">");
            }
            return RestResponse.success(fullRegion.toString());

        }

        return RestResponse.success(dictRegions);
    }

    @Override
    public RestResponse getAddressDetail(AddressDetailDto addressDetailDto) {

        //如果前台传递的参数为null则直接返回空
        if(!StringUtils.hasText(addressDetailDto.getAddress())){

            addressDetailDto.setAddress("");
            return RestResponse.success(addressDetailDto);

        }
        String newAddress = "";
        //获取前台传递过来的参数
        String address = addressDetailDto.getAddress();
        String[] split = address.split(",");
        for (String s : split) {
            //循环去查询数据
            DictRegion dictRegion = dictRegionMapper.selectById(s);
            newAddress += dictRegion.getName() + "/";
        }

        //处理掉最后一个/
        if (newAddress.endsWith("/")) {
            newAddress = newAddress.substring(0, newAddress.length() - 1);
        }
        addressDetailDto.setAddress(newAddress);

        return RestResponse.success(addressDetailDto);
    }


}
